package com.ssm.demo.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.github.pagehelper.util.StringUtil;
import com.ssm.demo.model.ManagerUser;
import com.ssm.demo.model.vo.UserVo;
import com.ssm.demo.service.manageruser.IManagerUserService;

/**
 * 
 * @ClassName: LoginController 
 * @Description: 登录Controller
 * @author Yin Qingsheng 
 * @date 2018年12月21日 上午11:12:00 
 *
 */
@Controller
@RequestMapping("/login")
public class LoginController {

	/**
	 * 日志
	 */
	private static Logger log = LoggerFactory.getLogger(LoginController.class);

	/**
	 * imanagerUserService
	 */
	@Resource
	private IManagerUserService imanagerUserService;

	/**
	 * 
	 * @Title: login
	 * @Description: 用户登录方法
	 * @param loginName 用户名
	 * @param password 密码
	 * @param session
	 * @param ra
	 * @return
	 * @return String
	 * @author Yin Qingsheng
	 * @date 2018年12月21日 上午11:12:20
	 * @throws
	 */
	@RequestMapping(value = "/toLogin")
	public String login(String loginName, String password, HttpSession session, Model model) {
		try {
			if (StringUtil.isEmpty(loginName) || StringUtil.isEmpty(password)) {
				model.addAttribute("username", loginName);
				model.addAttribute("password", password);
				model.addAttribute("message", "用户名或密码不能为空！！！");
				return "/login";
			}

			ManagerUser managerUser = imanagerUserService.findByLoginNameAndPassword(loginName, password);
			if (managerUser == null || managerUser.getId() == null) {
				model.addAttribute("username", loginName);
				model.addAttribute("password", password);
				model.addAttribute("message", "用户名不存在！！！");
				return "/login";
			}

			UserVo userVo = new UserVo();
			userVo.setUserId(managerUser.getId().toString());
			userVo.setUserName(managerUser.getName());
			userVo.setManagementType(managerUser.getManagementtype());
			if(managerUser.getManagementtype() == 0){
				userVo.setManagementTypeName("超级管理员");
			}else if(managerUser.getManagementtype() == 1){
				userVo.setManagementTypeName("借/还书管理员");
			}else if(managerUser.getManagementtype() == 2){
				userVo.setManagementTypeName("仓库管理员");
			}
			session.setAttribute("user", userVo);

			return "redirect:/main/index";
		} catch (Exception e) {
			log.error("登录异常", e);
		}
		return "login";

	}

	/**
	 * 
	 * @Title: exit
	 * @Description: 退出方法
	 * @param session
	 * @return
	 * @return String
	 * @author Yin Qingsheng
	 * @date 2018年12月21日 上午11:12:39
	 * @throws
	 */
	@RequestMapping(value = "/exit")
	public String exit(HttpSession session) {
		session.invalidate();
		return "login";
	}
}
